//
//  ButtonExt.swift
//  DYSwiftFramework
//
//  Created by huangdeyu on 2021/10/20.
//  Copyright © 2021 none. All rights reserved.
//

#if canImport(UIKit) && !os(watchOS)
import UIKit



private var tapKey:UInt8  = 0
protocol ButtonProtocol :AssociatedObjects {
    var onTap:((UIButton)->Void)? {get set}
    func tapAction(button:UIButton)
}

 
extension ButtonProtocol where Self :UIButton {
    var onTap:((UIButton)->Void)? {
        get {
            return associatedObject(for: &tapKey)
        }
        set(value){
            setAssociatedObject(value, for: &tapKey, policy: .copy)
            self.addTarget(self, action: #selector(tapAction), for: .touchUpInside)
        }
    }
}


// MARK: - Methods
extension UIButton : ButtonProtocol{
    @objc func tapAction(button: UIButton) {
        if let block = onTap {
            block(self)
        }
    }
    /// SwifterSwift: Center align title text and image.
    /// - Parameters:
    ///   - imageAboveText: set true to make image above title text, default is false, image on left of text.
    ///   - spacing: spacing between title text and image.
    func centerTextAndImage(imageAboveText: Bool = false, spacing: CGFloat) {
        if imageAboveText {
            // https://stackoverflow.com/questions/2451223/#7199529
            guard
                let imageSize = imageView?.image?.size,
                let text = titleLabel?.text,
                let font = titleLabel?.font else { return }

            let titleSize = text.size(withAttributes: [.font: font])

            let titleOffset = -(imageSize.height + spacing)
            titleEdgeInsets = UIEdgeInsets(top: 0.0, left: -imageSize.width, bottom: titleOffset, right: 0.0)

            let imageOffset = -(titleSize.height + spacing)
            imageEdgeInsets = UIEdgeInsets(top: imageOffset, left: 0.0, bottom: 0.0, right: -titleSize.width)

            let edgeOffset = abs(titleSize.height - imageSize.height) / 2.0
            contentEdgeInsets = UIEdgeInsets(top: edgeOffset, left: 0.0, bottom: edgeOffset, right: 0.0)
        } else {
            let insetAmount = spacing / 2
            imageEdgeInsets = UIEdgeInsets(top: 0, left: -insetAmount, bottom: 0, right: insetAmount)
            titleEdgeInsets = UIEdgeInsets(top: 0, left: insetAmount, bottom: 0, right: -insetAmount)
            contentEdgeInsets = UIEdgeInsets(top: 0, left: insetAmount, bottom: 0, right: insetAmount)
        }
    }
    
    
}

#endif
